package com.polarrose.spring.remoting.rest.support;

import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
import org.springframework.context.ApplicationContextException;

import com.polarrose.spring.remoting.rest.annotations.RestService;
import com.polarrose.spring.remoting.rest.RestController;
import com.polarrose.spring.remoting.rest.utils.RestServiceUtils;

public class RestUrlHandlerMapping extends AbstractUrlHandlerMapping
{
    public void initApplicationContext() throws ApplicationContextException
    {
        super.initApplicationContext();
        detectHandlers();
    }

    private void detectHandlers()
    {
        if (logger.isDebugEnabled()) {
            logger.debug("Looking for beans that are annotated with @RestService in application context: " + getApplicationContext());
        }

        for (String name : getApplicationContext().getBeanDefinitionNames())
        {
            Object bean = getApplicationContext().getBean(name);

            RestService restServiceAnnotation = bean.getClass().getAnnotation(RestService.class);
            if (restServiceAnnotation != null)
            {
                if (logger.isDebugEnabled()) {
                    logger.debug("Processing " + bean.getClass().getName());
                }

                // Create a RestController to wrap this @RestService

                RestController controller = new RestController();
                controller.setServiceObject(bean);
                try {
                    controller.afterPropertiesSet();
                } catch (Exception e) {
                    if (logger.isErrorEnabled()) {
                        logger.error("Cannot setup wrapper controller: " + e.getMessage(), e);
                    }
                }

                String urlPath = RestServiceUtils.getPathFromRestServiceClass(bean.getClass()) + "/**/*";
                registerHandler(urlPath, controller);

                if (logger.isDebugEnabled()) {
                    logger.debug("Registered " + bean + " on " + urlPath);
                }
            }
        }
    }
}
